package com.ccg.plat.presentation.ui.feature4.viewmodel

import android.app.Activity
import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.ZipUtils
import com.ccg.plat.presentation.common.base.viewmodel.BaseViewModelC
import com.ccg.plat.presentation.common.util.NavigationUtils
import com.ccg.plat.presentation.ui.feature3.model.RoomZipBean
import com.ccg.plat.presentation.ui.feature4.model.VideoBean
import com.ccg.plat.presentation.ui.feature4.model.VideoTagBean
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow

/**
 * @author : C4_雍和
 * 描述 :
 * 主要功能 :
 * 维护人员 : C4_雍和
 * date : 2025/8/9 8:49
 */
class VideoTagViewModel(application: Application) : BaseViewModelC(application) {
    //定义意图
    sealed class ContentIntent {
        class GoVideoListActivity(val activity: Activity, val url: String) : ContentIntent()
    }

    data class NaviViewState(var uiListData: List<VideoTagBean> = emptyList(), var tips: String = "")

    val newsChannel = Channel<ContentIntent>(Channel.UNLIMITED)
    var uiState by mutableStateOf(NaviViewState())

    init {
        handleIntent()
    }

    private fun handleIntent() {
        launch(Dispatchers.IO) {
            newsChannel.consumeAsFlow().collect { data ->
                when (data) {
                    is ContentIntent.GoVideoListActivity -> {
                        NavigationUtils.goVideoListActivity(context = data.activity, url = data.url)
                    }
                }
            }
        }
    }

    suspend fun initData(jsonStr: String?) {
        if (jsonStr.isNullOrEmpty()) {
            uiState = uiState.copy(tips = "服务器有问题请联系管理员")
        } else {
            val intentData = GsonBuilder().create().fromJson(jsonStr, RoomZipBean::class.java)
            val mJson = MMKV.defaultMMKV().decodeString(intentData.tag, "")
            if (mJson.isNullOrEmpty()) {
                //说明没有缓存过这个房间的数据,则正常联网请求,并缓存数据
                MMKV.defaultMMKV().encode(intentData.tag, jsonStr)
                val fileName = intentData.roomUrl.substring(intentData.roomUrl.lastIndexOf("/") + 1, intentData.roomUrl.length)
                val destPath = PathUtils.getInternalAppFilesPath() + "/${fileName}"
                if (FileUtils.isFileExists(destPath)) {
                    FileUtils.delete(destPath)
                }
                uiState = uiState.copy(tips = "首次进入需要下载视频列表大概需要2分钟左右请等待")
                val inputStream = retrofit.getNetData(intentData.roomUrl).byteStream()
                val isSuccessful = FileIOUtils.writeFileFromIS(destPath, inputStream)
                if (isSuccessful) {
                    val replacedString = fileName.replace(".zip", ".json")
                    if (FileUtils.isFileExists(replacedString)) {
                        FileUtils.delete(replacedString)
                    }
                    uiState = uiState.copy(tips = "下载成功正在解压")
                    ZipUtils.unzipFile(destPath, PathUtils.getInternalAppFilesPath())
                    FileUtils.delete(destPath)
                    uiState = uiState.copy(tips = "解压成功,正在对视频进行分类")
                    val jsonPath = PathUtils.getInternalAppFilesPath() + "/${replacedString}"
                    var json = FileIOUtils.readFile2String(jsonPath)
                    val listDatasOne = GsonBuilder().create().fromJson<List<VideoBean>>(json, object : TypeToken<List<VideoBean>>() {}.type)
                    json = ""
                    val videoTag: MutableList<String> = ArrayList()
                    val roomList: MutableList<VideoTagBean> = ArrayList()
                    val videoList: MutableList<VideoBean> = ArrayList()
                    for (i in listDatasOne) {
                        if (!videoTag.contains(i.tags)) {
                            videoTag.add(i.tags)
                        }
                    }
                    for (mTag in videoTag) {
                        var mId = 1
                        if (videoList.isNotEmpty()) {
                            videoList.clear()
                        }
                        for (mData in listDatasOne) {
                            if (mTag == mData.tags) {
                                videoList.add(VideoBean(id = mId, name = mData.name, pUrl = mData.pUrl, tags = mData.tags, vUrl = mData.vUrl))
                                mId += 1
                            }
                        }
                        roomList.add(VideoTagBean(name = intentData.roomUrl + mTag, tag = mTag))
                        MMKV.defaultMMKV().encode(intentData.roomUrl + mTag, GsonBuilder().create().toJson(videoList))
                    }
                    uiState = uiState.copy(uiListData = roomList)
                    MMKV.defaultMMKV().encode(intentData.roomUrl, GsonBuilder().create().toJson(roomList))
                    uiState = uiState.copy(tips = "")
                } else {
                    //如果缓存了数据,就拿缓存的和新传过来的数据进行对比,如果需要更新则删除缓存更新数据
                    uiState = uiState.copy(tips = "获取房间数据失败")
                }
            } else {
                val saveData = GsonBuilder().create().fromJson(mJson, RoomZipBean::class.java)
                if (saveData.timeStamp == intentData.timeStamp) {
                    //本地缓存的数据和服务器最新的数据一样则不需要更新缓存
                    val saveTagJson = MMKV.defaultMMKV().decodeString(intentData.roomUrl, "")
                    val listDatasOne = GsonBuilder().create().fromJson<List<VideoTagBean>>(saveTagJson, object : TypeToken<List<VideoTagBean>>() {}.type)
                    uiState = uiState.copy(uiListData = listDatasOne)
                } else {
                    //说明没有缓存过这个房间的数据,则正常联网请求,并缓存数据
                    MMKV.defaultMMKV().encode(intentData.tag, jsonStr)
                    val fileName = intentData.roomUrl.substring(intentData.roomUrl.lastIndexOf("/") + 1, intentData.roomUrl.length)
                    val destPath = PathUtils.getInternalAppFilesPath() + "/${fileName}"
                    if (FileUtils.isFileExists(destPath)) {
                        FileUtils.delete(destPath)
                    }
                    uiState = uiState.copy(tips = "首次进入需要下载视频列表大概需要2分钟左右请等待")
                    val inputStream = retrofit.getNetData(intentData.roomUrl).byteStream()
                    val isSuccessful = FileIOUtils.writeFileFromIS(destPath, inputStream)
                    if (isSuccessful) {
                        val replacedString = fileName.replace(".zip", ".json")
                        if (FileUtils.isFileExists(replacedString)) {
                            FileUtils.delete(replacedString)
                        }
                        uiState = uiState.copy(tips = "下载成功正在解压")
                        ZipUtils.unzipFile(destPath, PathUtils.getInternalAppFilesPath())
                        FileUtils.delete(destPath)
                        uiState = uiState.copy(tips = "解压成功,正在对视频进行分类")
                        val jsonPath = PathUtils.getInternalAppFilesPath() + "/${replacedString}"
                        var json = FileIOUtils.readFile2String(jsonPath)
                        val listDatasOne = GsonBuilder().create().fromJson<List<VideoBean>>(json, object : TypeToken<List<VideoBean>>() {}.type)
                        json = ""
                        val videoTag: MutableList<String> = ArrayList()
                        val roomList: MutableList<VideoTagBean> = ArrayList()
                        val videoList: MutableList<VideoBean> = ArrayList()
                        for (i in listDatasOne) {
                            if (!videoTag.contains(i.tags)) {
                                videoTag.add(i.tags)
                            }
                        }
                        for (mTag in videoTag) {
                            var mId = 1
                            if (videoList.isNotEmpty()) {
                                videoList.clear()
                            }
                            for (mData in listDatasOne) {
                                if (mTag == mData.tags) {
                                    videoList.add(VideoBean(id = mId, name = mData.name, pUrl = mData.pUrl, tags = mData.tags, vUrl = mData.vUrl))
                                    mId += 1
                                }
                            }
                            roomList.add(VideoTagBean(name = intentData.roomUrl + mTag, tag = mTag))
                            MMKV.defaultMMKV().encode(intentData.roomUrl + mTag, GsonBuilder().create().toJson(videoList))
                        }
                        uiState = uiState.copy(uiListData = roomList)
                        MMKV.defaultMMKV().encode(intentData.roomUrl, GsonBuilder().create().toJson(roomList))
                        uiState = uiState.copy(tips = "")
                    } else {
                        //如果缓存了数据,就拿缓存的和新传过来的数据进行对比,如果需要更新则删除缓存更新数据
                        uiState = uiState.copy(tips = "获取房间数据失败")
                    }
                }
            }
        }
    }
}
